package com.school.controller;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.Result;
import com.school.entity.Student;
import com.school.service.StudentService;
import com.school.service.DormitoryAllocationService;
import com.school.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 学生控制器
 */
@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private DormitoryAllocationService dormitoryAllocationService;
    
    /**
     * 添加学生
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody Student student) {
        Long id = studentService.add(student);
        return Result.success("添加成功", id);
    }
    
    /**
     * 更新学生
     */
    @PostMapping("/update")
    public Result<Void> update(@Validated @RequestBody Student student) {
        studentService.update(student);
        return Result.success("更新成功");
    }
    
    /**
     * 删除学生
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        studentService.delete(id);
        return Result.success("删除成功");
    }
    
    /**
     * 批量删除学生
     */
    @PostMapping("/batch-delete")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的学生");
            }
            log.info("批量删除学生，数量: {}", ids.size());
            int count = studentService.batchDelete(ids);
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success("批量删除成功，共删除 " + count + " 条数据", result);
        } catch (Exception e) {
            log.error("批量删除学生失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询学生
     */
    @GetMapping("/get/{id}")
    public Result<Student> getById(@PathVariable Long id) {
        Student student = studentService.getById(id);
        return Result.success(student);
    }
    
    /**
     * 分页查询学生列表
     */
    @GetMapping("/list")
    public Result<PageResult<Student>> getList(
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String building,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(pageNum);
        pageRequest.setPageSize(pageSize);
        
        PageResult<Student> pageResult = studentService.getPageList(
                studentId, name, className, building, status, pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 导入学生数据
     */
    @PostMapping("/import")
    public Result<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            List<Map<String, String>> dataList = ExcelUtils.importExcel(file.getInputStream());
            List<Student> students = new ArrayList<>();
            
            for (Map<String, String> data : dataList) {
                Student student = new Student();
                student.setStudentId(data.get("学号"));
                student.setName(data.get("姓名"));
                student.setGender(data.get("性别"));
                String ageStr = data.get("年龄");
                if (ageStr != null && !ageStr.isEmpty()) {
                    student.setAge(Integer.parseInt(ageStr));
                }
                student.setClassName(data.get("班级"));
                student.setBuilding(data.get("楼栋"));
                student.setDormitory(data.get("宿舍号"));
                student.setPhone(data.get("联系电话"));
                student.setStatus(data.get("状态"));
                student.setRemark(data.get("备注"));
                student.setBedNumber(data.get("床号"));

                students.add(student);
            }
            
            int count = studentService.batchImport(students);
            return Result.success("导入成功，共导入 " + count + " 条数据");
        } catch (Exception e) {
            log.error("导入学生数据失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出学生数据
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) {
        try {
            List<Student> students = studentService.getAllStudents();
            
            List<String> headers = Arrays.asList(
                    "学号", "姓名", "性别", "年龄", "班级", "班主任", "专业",
                    "楼栋", "宿舍号", "联系电话", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            for (Student student : students) {
                List<Object> row = Arrays.asList(
                        student.getStudentId(),
                        student.getName(),
                        student.getGender(),
                        student.getAge(),
                        student.getClassName(),
                        student.getTeacherName(),
                        student.getMajor(),
                        student.getBuilding(),
                        student.getDormitory(),
                        student.getPhone(),
                        student.getStatus(),
                        student.getRemark()
                );
                dataList.add(row);
            }
            
            String fileName = "学生列表_" + System.currentTimeMillis();
            ExcelUtils.exportExcel(response, fileName, "学生信息", headers, dataList);
        } catch (IOException e) {
            log.error("导出学生数据失败", e);
        }
    }
    
    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            List<String> headers = Arrays.asList(
                    "学号", "姓名", "性别", "年龄", "班级", "楼栋", "宿舍号", "联系电话", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            // 添加示例数据
            dataList.add(Arrays.asList(
                    "2023001", "张三", "男", 20, "计科2023-1班", "A栋", "101", "13800138001", "已入住", ""
            ));
            
            String fileName = "学生导入模板";
            ExcelUtils.exportExcel(response, fileName, "学生信息", headers, dataList);
        } catch (IOException e) {
            log.error("下载模板失败", e);
        }
    }
    
    /**
     * 自动分配宿舍
     */
    @PostMapping("/allocate-dormitory")
    public Result<Map<String, Object>> allocateDormitory() {
        try {
            log.info("开始执行自动分配宿舍");
            Map<String, Object> result = dormitoryAllocationService.autoAllocateDormitory();
            return Result.success("分配完成", result);
        } catch (Exception e) {
            log.error("自动分配宿舍失败", e);
            return Result.error("分配失败：" + e.getMessage());
        }
    }
}

